# git log master --since="2024-12-23" --no-merges --pretty=format:"- %s,([%h](https://gitee.com/openharmony-sig/ohos_react_native/commit/%H))" -- tester/harmony/react_native_openharmony > commit.md

ROOT_DIR=$(pwd)/..
SCRIPT_DIR=$ROOT_DIR/RNOH_Script
RNOH_DIR=$ROOT_DIR/react-native-harmony
TESTER_DIR=$ROOT_DIR/tester
HARMONY_DIR=$TESTER_DIR/harmony
RNOH_HARMONY=react_native_openharmony
RNOH_HARMONY_DIR=$HARMONY_DIR/$RNOH_HARMONY

if [ $# -eq 0 ]; then
    echo "[ERROR] please input version number (such as 0.72.50)"
    exit 1
fi

regex='^[0-9]+\.[0-9]+\.[0-9]+$'
if [[ ! $1 =~ $regex ]]; then
    echo "[ERROR] Version $1 is invalid (should be like 0.72.50)"
    exit 1
fi

# 更新CHANGELOG
function updateCHANGELOG() {
    # 读取版本号
    VERSION=$(cat $SCRIPT_DIR/version.txt)

    # 读取 CHANGELOG.md 的第一行
    FIRST_LINE=$(head -n 1 $ROOT_DIR/CHANGELOG.md)

    # 合并文件
    {
        echo "$FIRST_LINE"
        echo -e "\n## $VERSION\n$(cat $SCRIPT_DIR/outputs/commit.md)"
        tail -n +2 $ROOT_DIR/CHANGELOG.md
    } > CHANGELOG.tmp && mv CHANGELOG.tmp $ROOT_DIR/CHANGELOG.md
}

# 更新RNOH的CAHNGELOG
function updateRNOHCHANGELOG() {
    # 读取 CHANGELOG.md 的第一行
    FIRST_LINE=$(head -n 1 $RNOH_HARMONY_DIR/CHANGELOG.md)

    # 合并文件
    {
        echo "$FIRST_LINE"
        echo -e "\n## v$1\n$(cat $SCRIPT_DIR/outputs/commit.md)"
        tail -n +2 $RNOH_HARMONY_DIR/CHANGELOG.md
    } > CHANGELOG.tmp && mv CHANGELOG.tmp $RNOH_HARMONY_DIR/CHANGELOG.md
}

cd $ROOT_DIR

LAST_VERSION_DATE=$(head -n 1 $SCRIPT_DIR/changelogDate.txt)
LAST_DATE=$(echo "$LAST_VERSION_DATE" | awk '{print $2}')

git log master \
--since="$LAST_DATE" \
--no-merges \
--pretty=format:"- %s,([%h](https://gitee.com/openharmony-sig/ohos_react_native/commit/%H))" \
-- tester/harmony/react_native_openharmony \
> $SCRIPT_DIR/outputs/commit.md

updateCHANGELOG
updateRNOHCHANGELOG $1

CURRENT_DATE=$(date +%Y-%m-%d)
echo "$1 $CURRENT_DATE" | cat - $SCRIPT_DIR/changelogDate.txt > temp.txt && mv temp.txt $SCRIPT_DIR/changelogDate.txt
